package com.itheima.proxy.cglib.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author wz
 * @description:
 * @date 2021-10-31
 */
public class ProxyHonda {
    public static void main(String[] args) {
        // 创建目标对象
        Honda honda = new Honda();
        // 基于cglib生成代理对象
        Honda proxy = (Honda) Enhancer.create(honda.getClass(), new MethodInterceptor() {

            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

                Object result = null;
                //前置通知
                System.out.println("方法执行前运行.....");
                try {
                    result = method.invoke(honda, args);
                    //后置通知
                    System.out.println("方法成功执行后执行....");
                } catch (Exception e) {
                    // System.out.println(e.getMessage());
                    System.out.println("方法出现异常后运行.....");//异常通知
                } finally {
                    //最终通知
                    System.out.println("最终执行....");
                }
                return result;
            }
        });
        proxy.run();
    }
}
